<template>
  <!-- 规则定义子页面 -->
  <div>
    <div>
      <el-tabs @tab-click="changeTab" v-model="name" style="height: 500px">
        <el-tab-pane label="基本信息" name="0">
          <basicMsg
            ref="basicMsg"
            :ruleCode="ruleCode"
            :operateType="operateType"
          ></basicMsg>
        </el-tab-pane>
        <el-tab-pane label="数据来源" name="1">
          <data-source
            ref="dataSource"
            :ruleCode="ruleCode"
            :operateType="operateType"
          ></data-source>
        </el-tab-pane>
        <el-tab-pane label="分摊动因" name="2">
          <ca-agent
            ref="caAgent"
            :ruleCode="ruleCode"
            :operateType="operateType"
          ></ca-agent>
        </el-tab-pane>
        <el-tab-pane label="输出内容" name="3">
          <exportData
            ref="exportData"
            :ruleCode="ruleCode"
            :operateType="operateType"
          ></exportData
        ></el-tab-pane>
      </el-tabs>
      <div class="dialog-footer">
        <el-button
          @click="upStep"
          v-if="operateType != '3'"
          :disabled="name == '0'"
          >上一步</el-button
        >
        <el-button
          @click="nextStep"
          v-if="operateType != '3'"
          :disabled="name == '3'"
          >下一步</el-button
        >
        <el-button @click="toSave" v-if="operateType != '3'">保存</el-button>
      </div>
      <!-- 定位的备注 -->
      <div class="remark" v-if="operateType && operateType == '2'">
        <div class="img">
          <img
            src="@/assets/images/remark.png"
            alt="remark"
            @click="toShowRemark"
          />
          <p>备注</p>
        </div>
        <!-- <el-tag  @click="toShowRemark">备注</el-tag> -->
        <div class="ramarkTable" v-if="toShowRemarkDetails">
          <ca-rule-remark
            :blockType="blockType"
            :toShowRemarkDetails="toShowRemarkDetails"
            :ruleCode="ruleCode"
          ></ca-rule-remark>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { ruleDefinition } from "@/api/index";
import { publicManage } from "@/api/index";
// 基本信息
import basicMsg from "@/components/ca/basicMsg";
// 数据来源
import dataSource from "@/components/ca/dataSource";
// 分摊动因
import caAgent from "@/components/ca/caAgent";
// 输出内容
import exportData from "@/components/ca/exportData";
// 备注
import caRuleRemark from "@/components/ca/caRuleRemark";

export default {
  name: "ruleDefComponents",
  components: {
    basicMsg,
    dataSource,
    caAgent,
    exportData,
    caRuleRemark,
  },
  props: {
    ruleCode: {
      type: String,
      default: "",
    },
    operateType: {
      type: String,
      default: "1",
    },
  },
  data() {
    return {
      saveRuleCode: "",
      name: "0",
      toShowRemarkDetails: false,
      blockType: "ruleBase", // 规则定义是ruleBase,场景是ruleDriver
    };
  },
  // mounted() {
  //   this.showTabInit();
  // },
  // watch: {
  //   operateType(val) {
  //     this.showTabInit();
  //   },
  // },
  methods: {
    // 新增 编辑 复制 初始化
    showTabInit() {
      this.toShowRemarkDetails = false;
      this.name = "0";
      setTimeout(() => {
        this.$refs.basicMsg.clearMsg();
        this.$refs.dataSource.clearMsg();
        this.$refs.caAgent.clearMsg();
        this.$refs.exportData.clearMsg();
      }, 10);
    },
    toSave() {
      this.toCheckValid(); // 校验
    },
    // 检查校验
    toCheckValid() {
      this.$refs.basicMsg.$refs["addRuleBasic"].validate((valid) => {
        if (valid) {
          this.$refs.dataSource.$refs["addRuleSource"].validate((valid) => {
            if (valid) {
              // 当选择使用过滤器的时候过滤器选项必填
              let filterMethods = this.$refs.dataSource.addRuleSource
                .filterMethods;
              if (filterMethods == "1") {
                if (!this.$refs.dataSource.addRuleSource.filterCode) {
                  this.$message.warning("请选择过滤器");
                  this.name = "1";
                  return;
                }
              }
              this.$refs.caAgent.$refs["addRuleAgent"].validate((valid) => {
                if (valid) {
                  // 分摊动因相加不能超过1
                  let totalSumAll = this.$refs.caAgent.totalSumAll;
                  console.log(totalSumAll, "totalSumAll");
                  if (totalSumAll > 1 || totalSumAll <= 0) {
                    this.$message.warning(
                      "选择的动因比例之和不能大于1或者小于等于0"
                    );
                    this.name = "2";
                    return;
                  }
                  let addRuleInputs = this.$refs.caAgent.addRuleAgent
                    .addRuleInput;
                  for (let i = 0; i < addRuleInputs.length; i++) {
                    if (addRuleInputs[i].driverP == 0) {
                      this.$message.warning("输入的动因比例不能为0");
                      this.name = "2";
                      return;
                    }
                  }
                  this.$refs.exportData.$refs["addRuleExport"].validate(
                    (valid) => {
                      if (valid) {
                        this.basicMsgToSave();
                      } else {
                        this.$message.warning("请补充完整信息");
                        this.name = "3";
                      }
                    }
                  );
                } else {
                  this.$message.warning("请补充完整信息");
                  this.name = "2";
                }
              });
            } else {
              this.$message.warning("请补充完整信息");
              this.name = "1";
            }
          });
        } else {
          this.$message.warning("请补充完整信息");
          this.name = "0";
        }
      });
    },
    basicMsgToSave() {
      let basicMsg = this.$refs.basicMsg.addRuleBasic;
      // 基础信息保存 规则名称规则类型
      this.$refs.basicMsg.$refs["addRuleBasic"].validate((valid) => {
        if (valid) {
          let params = {
            operateType: this.operateType,
            ruleBase: {
              desn: basicMsg.desn,
              driverType: basicMsg.driverType, // 分摊方法
              ruleCode: basicMsg.ruleCode,
              ruleName: basicMsg.ruleName,
              ruleOperator: "*",
              ruleType: basicMsg.ruleType,
              sceneCode: basicMsg.sceneCode, // 所属场景
              descn: basicMsg.descn,
            },
          };
          ruleDefinition
            .ruleBaseSave(params)
            .then((res) => {
              if (res.code == 200 && res.success) {
                console.log("基础信息的保存");
                // 数据来源的保存
                this.saveRuleCode = res.data;
                this.dataSourceToSave();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          this.$message.error("请补充完整信息");
          this.name = "0";
        }
      });
    },
    dataSourceToSave() {
      let dataSource = this.$refs.dataSource.addRuleSource;
      let selectConditionList = this.$refs.dataSource.selectConditionList;
      for (let i = 0; i < selectConditionList.length; i++) {
        console.log(selectConditionList[i], "selectConditionList[i]");
        (selectConditionList[i].dimId =
          selectConditionList[i].relatedDimensionCode),
          (selectConditionList[i].dimValue = selectConditionList[i].columnEn),
          // (selectConditionList[i].dimValue = ""),
          (selectConditionList[i].pubPhysicalcolumnId =
            selectConditionList[i].columnEn),
          console.log(selectConditionList[i], "ruleDatafilterList[i]");
      }
      for (let i = 0; i < selectConditionList.length; i++) {
        console.log(
          selectConditionList[i].filterValue,
          "selectConditionList[i].filterValue"
        );
        if (selectConditionList[i].filterValue == "") {
          selectConditionList.splice(i, 1);
          console.log("123321");
          i = i - 1;
        }
      }
      // 数据来源的信息保存 规则名称规则类型
      // selectConditionList
      this.$refs.dataSource.$refs["addRuleSource"].validate((valid) => {
        if (valid) {
          if (this.operateType == "5") {
            // 复制
            dataSource.datafilterId = "";
          }
          let params = {
            operateType: this.operateType,
            pcolumnId: dataSource.columnEn,
            ruleBaseDetail: {
              datafilterId: dataSource.datafilterId, // 主建id
              balanceType: "", // 分摊类型
              elementType: "1", // 第二个tab
              filterId: dataSource.filterCode, // 过滤表id
              filterType: dataSource.filterMethods, // 过滤类型
              pubPhysicalcolumnId: dataSource.columnEn, // 字段值
              pubPhysicaltableId: dataSource.tableNameEn, // 表值
              ruleCode: this.saveRuleCode, // 上个接口返回的编码
              feeType: dataSource.feeType,
              fieldCode: "", // 账户费用接收字段 （输出结果使用）
            },
            ruleDatafilterList: selectConditionList,
          };
          ruleDefinition
            .ruleBaseDetailSave(params)
            .then((res) => {
              if (res.code == 200 && res.success) {
                console.log("数据来源的的保存");
                // 分摊动因的保存
                this.caAgentToSave();
              } else {
                this.$message.error(res.message);
                this.$emit("closeToQuery", "aa");
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          this.$message.error("请补充完整信息");
          this.name = "1";
        }
      });
    },
    // 分摊动因的保存
    caAgentToSave() {
      let caAgent = this.$refs.caAgent.addRuleAgent;
      let addRuleInput = this.$refs.caAgent.addRuleAgent.addRuleInput;
      for (let i = 0; i < addRuleInput.length; i++) {
        (addRuleInput[i].driverCode = addRuleInput[i].driverC),
          (addRuleInput[i].driverPercent = addRuleInput[i].driverP),
          (addRuleInput[i].driverOperator = "*");
      }
      // 分摊动因的信息保存
      this.$refs.caAgent.$refs["addRuleAgent"].validate((valid) => {
        if (valid) {
          let params = {
            operateType: this.operateType,
            elementType: "2",
            ruleCode: this.saveRuleCode, // 接口返回的
            ruleOperator: "*", // 规则算符
            ruleBaseDriverList: addRuleInput,
          };
          ruleDefinition
            .ruleBaseDriverSave(params)
            .then((res) => {
              if (res.code == 200 && res.success) {
                console.log("分摊动因的保存");
                // 输出内容的保存
                this.exportDataToSave();
              } else {
                this.$message.error(res.message);
                this.$emit("closeToQuery", "aa");
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          this.$message.error("请补充完整信息");
          this.name = "2";
        }
      });
    },
    // 输出内容保存
    exportDataToSave() {
      let exportData = this.$refs.exportData.addRuleExport;
      let selectConditionList = this.$refs.exportData.selectConditionList;
      for (let i = 0; i < selectConditionList.length; i++) {
        (selectConditionList[i].dimId =
          selectConditionList[i].relatedDimensionCode),
          (selectConditionList[i].dimValue = selectConditionList[i].columnEn),
          // (selectConditionList[i].dimValue = ""),
          (selectConditionList[i].filterDesc =
            selectConditionList[i].filterDesc),
          (selectConditionList[i].filterName =
            selectConditionList[i].filterName),
          (selectConditionList[i].filterValue =
            selectConditionList[i].filterValue),
          (selectConditionList[i].pubPhysicalcolumnId =
            selectConditionList[i].columnEn),
          (selectConditionList[i].selectionFlag =
            selectConditionList[i].selectionFlag),
          (selectConditionList[i].treeId = selectConditionList[i].treeId);
      }
      // 输出内容的信息保
      let basicMsg = this.$refs.basicMsg.addRuleBasic;
      this.$refs.exportData.$refs["addRuleExport"].validate((valid) => {
        if (valid) {
          if (this.operateType == "5") {
            // 复制
            exportData.datafilterId = "";
          }
          let params = {
            debitDatafilterId: exportData.debitDatafilterId, // 维度筛选code
            debitFlag: "1",
            operateType: this.operateType,
            debitPubPhysicaltableId: exportData.pubPhysicaltableId,
            debitPubPhysicalcolumnId: exportData.pubPhysicalcolumnId,
            feeField: exportData.feeField, // 账户标示
            elementType: "3",
            ruleDatafilterList: selectConditionList,
            ruleType: basicMsg.ruleType,
            ruleCode: basicMsg.ruleCode,
          };
          ruleDefinition
            .ruleBaseDetailSaveOutPut(params)
            .then((res) => {
              if (res.code == 200 && res.success) {
                // 关闭弹窗，调用规则定义列表查询
                this.$message.success("数据保存成功");
                this.$emit("closeToQuery", "aa");
              } else {
                this.$message.error(res.message);
                this.$emit("closeToQuery", "aa");
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          this.$message.error("请补充完整信息");
          this.name = "3";
        }
      });
    },
    upStep() {
      this.name = Number(this.name) - 1 + "";
    },
    nextStep() {
      this.name = Number(this.name) + 1 + "";
      if (this.name == "3") {
        setTimeout(() => {
          if (!this.$refs.exportData.addRuleExport.pubPhysicaltableId) {
            this.$refs.exportData.ruleTypeChange();
            this.$refs.exportData.addRuleSource();
          }
        }, 10);
      }
    },
    // 选择tab进行页面切换
    changeTab(val) {
      console.log(val, "val");
      if (this.name == "3") {
        setTimeout(() => {
          if (!this.$refs.exportData.addRuleExport.pubPhysicaltableId) {
            this.$refs.exportData.ruleTypeChange();
            this.$refs.exportData.addRuleSource();
          }
          this.$refs.exportData.ruleTypeChange();
          this.$refs.exportData.addRuleSource();
        }, 10);
      }
    },
    toShowRemark() {
      this.toShowRemarkDetails = !this.toShowRemarkDetails;
    },
  },
};
</script>
<style lang="scss" scoped>
// .remark img {
//   position: absolute;
//   left: 0;
//   bottom: 10%;
//   opacity: 0.7;
//   z-index: 999;
// }
// .remark img:hover {
//   opacity: 1;
//   z-index: 999;
// }
.remark .img {
  position: absolute;
  left: 0;
  bottom: 10%;
  opacity: 0.8;
  z-index: 999;
}
.remark .img:hover {
  opacity: 1;
  z-index: 999;
}
.remark .ramarkTable {
  background-color: white;
  position: absolute;
  right: 0;
  bottom: 60px;
  z-index: 666;
  width: 100%;
  border: 1px solid #ccc;
}
.remark p {
  text-align: center;
  line-height: 20px;
  color: #445375;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  padding: 16px;
}
</style>